package cn.tedu.wxdemo.service;

import cn.tedu.wxdemo.domain.AccessTokenBean;
import cn.tedu.wxdemo.util.HttpClientUtil;
import cn.tedu.wxdemo.util.WxCharConstant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class WxServiceImpl implements WxService{
    @Value("${wx.appid}")
    private String appId;
    @Value("${wx.appsecret}")
    private String secret;
    
    private AccessTokenBean accessTokenBean;

    @Override
    public String getAccessToken() {
        
        if (accessTokenBean == null || accessTokenBean.isExpired()){
            synchronized (this){
                refreshTolen(appId,secret);
            }
        }
        return accessTokenBean.getAccessToken();
    }

    private void refreshTolen(String appId, String secret) {
        String url = WxCharConstant.ACCESS_TOKEN
                .replace("APPID", appId)
                .replace("APPSECRET", secret);
        String s = HttpClientUtil.doGet(url);
        System.out.println(s);
        JSONObject jsonObject = JSON.parseObject(s);
        String accessToken = jsonObject.getString("access_token");
        String expiressIn = jsonObject.getString("expires_in");
        accessTokenBean = AccessTokenBean.responseOf(accessToken,Long.parseLong(expiressIn));
        System.out.println(s);
    }
}
